from flask import Blueprint, request, jsonify, current_app

from app.src.user import user_bp
from app.src.user.services import UserService
# 移除顶层导入，改为在需要时导入
# from app.src.auth.services import AuthService



@user_bp.before_request
def check_auth():
    from app.src.auth.services import AuthService
    # 跳过不需要验证的路由
    # if request.endpoint and not request.endpoint.startswith('user.'):
    #     return

    token = request.headers.get('Authorization')
    if not token:
        return jsonify({
            'code': 401,
            'message': '未提供认证token'
        }), 401

    auth_service = AuthService()
    result = auth_service.verify_token(token)

    if not result.get('valid'):
        return jsonify({
            'code': 401,
            'message': result.get('message', 'token无效或已过期')
        }), 401

# 获取单个信息
@user_bp.route('/info', methods=['GET'])
def get_user_info():
    user_id = request.args.get('user_id')
    current_app.logger.info(f"获取用户信息，user_id: {user_id}")
    user = UserService()
    result = user.get_profile(user_id)
    return jsonify(result)

# 获取列表
@user_bp.route('/list', methods=['GET'])
def get_user_list():
    page = int(request.args.get('page', 1))
    page_size = int(request.args.get('page_size', 10))
    current_app.logger.info(f"获取用户列表，page: {page}, page_size: {page_size}")
    
    user = UserService()
    users = user.get_user_list(page=page, page_size=page_size)
    return jsonify(users)

# 创建用户
@user_bp.route('/create', methods=['POST'])
def create_user():
    data = request.json
    current_app.logger.info(f"创建新用户，数据: {data}")
    user = UserService()
    result = user.create_user(data)
    return jsonify({"message": "User created successfully", "id": result})

